// Copyright 2009, Lucid Technics, LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in
// writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.

importClass(Packages.org.tmatesoft.svn.core.SVNDirEntry);
importClass(Packages.org.tmatesoft.svn.core.SVNURL);
importClass(Packages.org.tmatesoft.svn.core.io.SVNRepository);
importClass(Packages.org.tmatesoft.svn.core.io.SVNRepositoryFactory);
importClass(Packages.org.tmatesoft.svn.core.internal.io.fs.FSRepositoryFactory);
importClass(Packages.java.io.File);

var svnRepositoryList = h.l(),
    repositoryRoot = SERVLET.getServletConfig().getInitParameter("rr.repository.root");

CONTENT_CONTEXT.type = "application/xhtml+xml";

FSRepositoryFactory.setup();

try
{
	var repositoryDirectory = new File(repositoryRoot);	
	var repositoryFiles = repositoryDirectory.listFiles();

	if (h.isDefined(repositoryFiles) === true)
	{
		for (var i = 0; i < repositoryFiles.length; i++)
		{
			var file = repositoryFiles[i];

			if (h.isDefined(file) === true &&
				  file.exists() === true &&
				  file.isDirectory() === true)
			{
				var url = SVNURL.parseURIDecoded("file:///" + file.getAbsolutePath().replaceAll("^/", ""));
				var repository = SVNRepositoryFactory.create(url);
				var path = repository.getRepositoryRoot(true).getPath();
				var info = repository.info("/", 0);

				if (h.isDefined(info) === true)
				{
					var svnRepository = h.ar();

					svnRepository.name = file.name;
					svnRepository.root = repositoryRoot;
					svnRepository.lastModifiedDate = info.date;
					svnRepository.status = "active";
					svnRepository.revision = info.revision;
					svnRepository.lastAuthor = info.author;
					svnRepository.URL = url;

					svnRepositoryList.add(svnRepository);
				}
			}
		}

		CONTENT_CONTEXT.content = h.ar().table({activeRecordList: svnRepositoryList, include: "name, lastModifiedDate, root, revision, status, lastAuthor, URL"});
	}
	else
	{
		var emptyList = h.l();
		CONTENT_CONTEXT.content = h.ar().table({activeRecordList: emptyList });
	}	
}
catch(e)
{
	LOG.error("Encountered exception:" + e + " while trying to get repository list.");
	CONTENT_CONTEXT.content = h.msg500();
}